package com.kim.rssreader.activity;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import cn.waps.AdView;
import cn.waps.AppConnect;
import cn.waps.UpdatePointsNotifier;

import com.kim.rssreader.R;
import com.kim.rssreader.adapter.ColumnGridAdapter;
import com.kim.rssreader.adapter.ColumnViewPageAdapter;
import com.kim.rssreader.domain.AbstractDomain;
import com.kim.rssreader.domain.RssCategory;
import com.kim.rssreader.domain.RssColumn;
import com.kim.rssreader.utils.DigestUtils;
import com.kim.rssreader.utils.ValueConstant;
import com.kim.rssreader.view.PopMenu;

public class MainActivity extends BaseActivity implements UpdatePointsNotifier {

	// RSS栏目类别
	List<RssCategory> categories;
	List<String> categoryNames;

	// RSS栏目
	List<RssColumn> columns;

	Spinner spinnerCategory;// RSS类别选框

	ViewPager viewPager;

	View rssColumnView;

	GridView rssColumnGridView;

	Button addColumn;

	List<View> views;

	Button btn_menu;
	Button btn_add;
	TextView txt_rssCount;// 当前类别下RSS源数量
	// PopupWindow popMenu;

	PopMenu popMenu = null;

	TextView txv_result;

	private String result;

	Handler myhandler = new Handler();

	public static MainActivity mainActivity = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setAD();// 广告设置
	}

	@Override
	protected void onResume() {
		super.onResume();
		showColumn();
		refreshViewPager();
		mainActivity = this;
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		return super.onTouchEvent(event);
	}

	@Override
	public void initView() {

		setContentView(R.layout.main_activity);
		txt_rssCount = (TextView) findViewById(R.id.txt_rsscount);
		spinnerCategory = (Spinner) findViewById(R.id.spinner_rsscategory);
		addColumn = (Button) findViewById(R.id.btn_addCustomerRss);

		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				R.layout.rss_main_spinner_items, categoryNames);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinnerCategory.setAdapter(adapter);
		spinnerCategory.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				String categoryId = categories.get(position).rssCategoryId;
				getColumnData(categoryId);
				updateRssCount();
				showColumn();
				refreshViewPager();

				// 更新rss类别关注度
				dbDAO.updateCategoryAttention(categoryId);
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {

			}
		});

		// 首页右上角菜单
		btn_menu = (Button) findViewById(R.id.btn_menu);
		btn_menu.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				showMenu();
			}
		});
		btn_add = (Button) findViewById(R.id.btn_addCustomerRss);
		btn_add.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				// 等待添加
			}
		});

		viewPager = (ViewPager) findViewById(R.id.vp_rssColumn);

		LayoutInflater inflater = (LayoutInflater) this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		rssColumnView = inflater.inflate(R.layout.rss_column_grid_view, null);

		rssColumnGridView = (GridView) rssColumnView
				.findViewById(R.id.gv_rss_column);
		rssColumnView.setPadding(ValueConstant.GRID_HORIZONTALSPACING,
				ValueConstant.GRID_HORIZONTALSPACING, 0, 0);

		rssColumnGridView
				.setOnItemClickListener(new AdapterView.OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {

						RssColumn column = (RssColumn) parent
								.getItemAtPosition(position);

						// 更新栏目关注度
						dbDAO.updateColumnAttention(column.rssColumnID);

						Intent intent = new Intent();
						intent.setClass(MainActivity.this,
								RSSContentListActivity.class);
						intent.putExtra("columnid", column.rssColumnID);
						intent.putExtra("url", column.rssColumnUrl);
						intent.putExtra("value", column.rssColumnName);
						intent.putExtra("flagStart", column.rssColumnFlagStart);
						intent.putExtra("flagEnd", column.rssColumnFlagEnd);
						intent.putExtra("category", categoryNames
								.get(spinnerCategory.getSelectedItemPosition()));
						startActivity(intent);
					}

				});

		// 添加订阅源
		addColumn.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this,
						SubscribeCategoryActivity.class);
				startActivity(intent);
			}
		});
	}

	@Override
	public void initParam() {
		getRssCategoryData();
		getColumnData(categories.get(0).rssCategoryId);
	}

	private void showColumn() {
		ColumnGridAdapter adapter = (ColumnGridAdapter) rssColumnGridView
				.getAdapter();
		if (adapter == null) {
			adapter = new ColumnGridAdapter(this, columns);
			rssColumnGridView.setAdapter(adapter);
		} else {
			adapter.resetData(columns);
		}
		adapter.notifyDataSetChanged();
	}

	/**
	 * 刷新栏目列表
	 */
	private void refreshViewPager() {
		if (views != null) {
			views.clear();
			views = null;
		}

		if (viewPager != null) {
			viewPager.removeAllViews();
		}

		views = new ArrayList<View>();

		views.add(rssColumnView);

		ColumnViewPageAdapter viewPageAdapter = (ColumnViewPageAdapter) viewPager
				.getAdapter();
		if (viewPageAdapter == null) {
			viewPageAdapter = new ColumnViewPageAdapter(views);
			viewPager.setAdapter(viewPageAdapter);
		} else {
			viewPageAdapter.resetData(views);
		}
		viewPageAdapter.notifyDataSetChanged();
		viewPager.setCurrentItem(0);
	}

	/**
	 * 获取栏目类别
	 */
	private void getRssCategoryData() {
		List<AbstractDomain> abstractDomains = dbDAO.getRssCategory();

		// 获取RSS栏目类别
		categories = new ArrayList<RssCategory>();
		categoryNames = new ArrayList<String>();
		if (abstractDomains != null && abstractDomains.size() > 0) {

			for (AbstractDomain domain : abstractDomains) {
				categories.add((RssCategory) domain);
				categoryNames.add(((RssCategory) domain).rssCategoryName);
			}
			abstractDomains.clear();
		}
		abstractDomains = null;
	}

	/**
	 * 获取栏目列表
	 * 
	 * @param categoryID
	 */
	private void getColumnData(String categoryID) {

		if (columns != null) {
			columns.clear();
			columns = null;
		}

		List<AbstractDomain> abstractDomains;
		columns = new ArrayList<RssColumn>();
		// 获取RSS栏目列表 默认第一个类别下所有栏目

		// 查看类别显示所有栏目前10条
		boolean isFrequent = false;
		if (DigestUtils.shaHex(ValueConstant.COLUMN_ALL).equals(categoryID)) {
			isFrequent = true;
		}

		abstractDomains = dbDAO.getColumnByCategory(categoryID, isFrequent);
		if (abstractDomains != null && abstractDomains.size() > 0) {

			for (AbstractDomain domain : abstractDomains) {
				columns.add((RssColumn) domain);
			}
			abstractDomains.clear();
			abstractDomains = null;
		}
	}

	private void updateRssCount() {
		if (columns != null) {
			txt_rssCount.setText("共" + columns.size() + "个RSS源");
		} else {
			txt_rssCount.setText("共0个RSS源");
		}
	}

	// 右上角菜单
	private void showMenu() {
		if (popMenu != null && popMenu.isShowing()) {
			popMenu.dismiss();
			return;
		}
		if (popMenu == null) {
			popMenu = new PopMenu(MainActivity.this, Gravity.TOP
					| Gravity.RIGHT, R.style.magazinePopMenuStyle);
		}
		popMenu.show();
	}

	/**
	 * 万普广告
	 */
	// 获取虚拟货币余额:
	private void getPoints() {
		AppConnect.getInstance(this).getPoints(this);
	}

	// 花费用户虚拟货币
	private void spendPoints(int amount) {
		AppConnect.getInstance(this).spendPoints(amount,
				(UpdatePointsNotifier) this);
	}

	// 奖励用户虚拟货币
	private void awardPoints(int amount) {
		AppConnect.getInstance(this).awardPoints(amount,
				(UpdatePointsNotifier) this);
	}

	// 获取成功
	public void getUpdatePoints(String currencyName, int pointTotal) {
		System.out.println("hebaoxiang" + currencyName + pointTotal);
		result = currencyName + ": " + pointTotal;
		myhandler.post(mUpdateResults);
	}

	// 获取失败
	public void getUpdatePointsFailed(String error) {
		System.out.println("hebaoxiang" + error);
		Toast.makeText(this, "获取成功虚拟货币失败。 " + error, Toast.LENGTH_SHORT).show();
	}

	// 创建一个线程刷新UI显示货币信息
	final Runnable mUpdateResults = new Runnable() {
		public void run() {
			// 显示虚拟货币结果
			// if (txv_result != null) {
			// txv_result.setText(result);
			// }
		}
	};

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_MENU:
			showMenu();
			break;
		default:
			break;
		}
		return super.onKeyDown(keyCode, event);
	}

	// 广告初始化
	private void setAD() {
		/**
		 * 替换广告方法： 1、将下面的广告代码注释替换掉； 2、将布局文件中的android:visibility="gone"替换
		 */

		/**
		 * 有米广告
		 */
		// 积分条
		// AdManager.init(this, "1fe963a7ee603cc1", "95c1803980412d15", 30,
		// false);
		// LinearLayout adViewLayout = (LinearLayout)
		// findViewById(R.id.adViewLayout);
		// adViewLayout.addView(new AdView(this), new LayoutParams(
		// LinearLayout.LayoutParams.FILL_PARENT,
		// LinearLayout.LayoutParams.WRAP_CONTENT));
		// //
		// // // 积分墙
		// YoumiOffersManager.init(this, "1fe963a7ee603cc1",
		// "95c1803980412d15");
		//
		// // 有米推
		// YoumiPush.startYoumiPush(this, "1fe963a7ee603cc1",
		// "95c1803980412d15",
		// false);

		/**
		 * 万普广告条
		 */
		LinearLayout container = (LinearLayout) findViewById(R.id.AdLinearLayout);
		new AdView(this, container).DisplayAd();

	}
}
